package edu.study.api.common.constraints;

import org.apache.commons.lang.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DateValidator implements ConstraintValidator<FormattedDate, String> {

    private Pattern pattern;

    @Override
    public boolean isValid(String dateStr, ConstraintValidatorContext context) {

        if (StringUtils.isBlank(dateStr)) {
            return true;
        }
        Matcher m = pattern.matcher(dateStr);
        return m.matches();
    }

    @SuppressWarnings("rawtypes")
    @Override
    public void initialize(FormattedDate constraintAnnotation) {
        this.pattern = Pattern.compile(constraintAnnotation.regexp());
    }

}
